package com.example.yjj_java_web_homework3.service.impl;

import com.example.yjj_java_web_homework3.entity.Device;
import com.example.yjj_java_web_homework3.repository.DeviceRepository;
import com.example.yjj_java_web_homework3.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @author Li Chun Hei
 * @date 4/11/2025
 * @description
 */
@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceRepository deviceRepository;

    @Override
    @Transactional
    public Device createDevice(Device device) {
        if (deviceRepository.existsBySerialNumber(device.getSerialNumber())) {
            throw new RuntimeException("设备序列号已存在");
        }
        return deviceRepository.save(device);
    }

    @Override
    @Transactional
    public Device updateDevice(Long id, Device device) {
        Device existingDevice = deviceRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("设备不存在"));

        if (!existingDevice.getSerialNumber().equals(device.getSerialNumber()) &&
                deviceRepository.existsBySerialNumber(device.getSerialNumber())) {
            throw new RuntimeException("设备序列号已存在");
        }

        existingDevice.setName(device.getName());
        existingDevice.setModel(device.getModel());
        existingDevice.setSerialNumber(device.getSerialNumber());
        existingDevice.setDescription(device.getDescription());
        existingDevice.setStatus(device.getStatus());

        return deviceRepository.save(existingDevice);
    }

    @Override
    @Transactional
    public void deleteDevice(Long id) {
        if (!deviceRepository.existsById(id)) {
            throw new RuntimeException("设备不存在");
        }
        deviceRepository.deleteById(id);
    }

    @Override
    public Device getDeviceById(Long id) {
        return deviceRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("设备不存在"));
    }

    @Override
    public List<Device> getAllDevices() {
        return deviceRepository.findAll();
    }

    @Override
    public Page<Device> getDevicesByPage(Pageable pageable) {
        return deviceRepository.findAll(pageable);
    }

    @Override
    public List<Device> getDevicesByStatus(Device.DeviceStatus status) {
        return deviceRepository.findByStatus(status);
    }

    @Override
    @Transactional
    public Device updateDeviceStatus(Long id, Device.DeviceStatus status) {
        Device device = getDeviceById(id);
        device.setStatus(status);
        return deviceRepository.save(device);
    }
}

